package com.itheima.easy.intercept;

import com.itheima.easy.security.JwtTokenManager;
import com.itheima.easy.constant.SecurityConstant;
import com.itheima.easy.constant.UserCacheConstant;
import com.itheima.easy.utils.EmptyUtil;
import com.itheima.easy.utils.UserThreadLocal;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName TenantIntercept.java
 * @Description 多租户放到SubjectContent上下文中
 */
@Component
public class UserTokenIntercept implements HandlerInterceptor {

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    JwtTokenManager jwtTokenManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        //从头部中拿到当前userToken
        String userToken = request.getHeader(SecurityConstant.USER_TOKEN);
        if (!EmptyUtil.isNullOrEmpty(userToken)){
            String jwtTokenKey = UserCacheConstant.JWT_TOKEN+userToken;
            RBucket<String> jwtTokenKeyBucket = redissonClient.getBucket(jwtTokenKey);
            if (!EmptyUtil.isNullOrEmpty(jwtTokenKeyBucket.get())){
                String currentUser = String.valueOf(jwtTokenManager.getCurrentUser(jwtTokenKeyBucket.get()));
                //放入当前线程中：用户当前的web直接获得user使用
                UserThreadLocal.setSubject(currentUser);
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除当前线程中的参数
        UserThreadLocal.removeSubject();
    }
}
